import {Component, OnInit} from '@angular/core';
import {FormGroup, FormControl, Validators, FormBuilder} from '@angular/forms';
import {Router} from '@angular/router';

@Component({
  selector: 'app-forget-password',
  templateUrl: './forget-password.component.html',
  styleUrls: ['./forget-password.component.scss']
})
export class ForgetPasswordComponent implements OnInit {
  resetType = 'sms';
  step = 'valid';
  countdownSecond = 0;
  timer;
  forgetPasswordForm: FormGroup;
  mobile = new FormControl('', [
    Validators.required,
    Validators.pattern(/^(1(([358][0-9]|7[2-9])|(47)))\d{8}$/)
  ]);
  email = new FormControl('', [
    Validators.required,
    Validators.pattern('[\\w]+?@[\\w]+?\\.[a-z]+?')
  ]);
  resetPasswordForm: FormGroup;
  verifyCode = new FormControl('', [
    Validators.required
  ]);
  newPassword = new FormControl('', [
    Validators.required,
    Validators.minLength(8),
    Validators.maxLength(20)
  ]);
  repeatPassword = new FormControl('', [
    Validators.required,
    this.passwordMatch
  ]);

  private passwordMatch() {
    return (c: FormControl) => {
      return (c.value === this.newPassword.value) ? null : {'passwordMatch': {valid: false}};
    };
  }

  constructor(private formBuilder: FormBuilder, private router: Router) {
  }

  ngOnInit() {
    this.forgetPasswordForm = this.formBuilder.group({
      mobile: this.mobile,
      email: this.email
    });

    this.resetPasswordForm = this.formBuilder.group({
      verifyCode: this.verifyCode,
      newPassword: this.newPassword,
      repeatPassword: this.repeatPassword
    });
  }

  setClassMobile() {
    return {'has-danger': !this.mobile.pristine && !this.mobile.valid};
  }

  setClassEmail() {
    return {'has-danger': !this.email.pristine && !this.email.valid};
  }

  setClassVerifyCode() {
    return {'has-danger': !this.verifyCode.pristine && !this.verifyCode.valid};
  }

  setClassNewPassword() {
    return {'has-danger': !this.newPassword.pristine && !this.newPassword.valid};
  }

  setClassRepeatPassword() {
    return {'has-danger': !this.repeatPassword.pristine && !this.repeatPassword.valid};
  }

  onChangeRestType(value) {
    this.resetType = value;
  }

  countdown() {
    if (this.countdownSecond <= 0) {
      return false;
    }
    this.countdownSecond--;
  }

  forgetPassword() {
    const _this = this;
    _this.step = 'reset';
    _this.countdownSecond = 10;
    clearInterval(_this.timer);
    this.timer = setInterval(() => _this.countdown(), 1000);
  }

  backToValid() {
    this.step = 'valid';
  }

  resetPassword() {
    /*const _this = this;
    this.toast.setMessage('重置密码成功，即将返回登录页面', 'success');
    setTimeout(() => _this.router.navigate(['/login']), 3500);*/
  }
}
